package cn.acewill.yxd.yunxundian.ui.user;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.adapter.PersonEfficRecycleAdapter;
import cn.acewill.yxd.yunxundian.model.ManagerEfficBean;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.utils.TopDialogUtils;

/**
 * Created by AAA on 2017/4/12.
 */

public class    PersonEfficForOMActivity extends BaseActivity implements View.OnClickListener {

    private RecyclerView myList;
    private  ArrayList<ManagerEfficBean> melist;
    private PersonEfficRecycleAdapter adapter;
    private Dialog dialog;
    private int year,month,userId,thisyear,thismonth;
    private TextView noNetWork,title_bar;
    private RelativeLayout loadingRel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.person_effic_info_om_list);
        initView();
        initRecycle();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_morebtn,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.MoreBtn:
                creatMoreDialog();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initView(){
        Toolbar mytoolbar = (Toolbar) findViewById(R.id.myToolBar);
        mytoolbar.setTitle("");
        mytoolbar.setNavigationIcon(R.mipmap.back);
        setSupportActionBar(mytoolbar);
        mytoolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        title_bar= (TextView) findViewById(R.id.title_bar);
        Calendar ca=Calendar.getInstance();
         year=ca.get(Calendar.YEAR);
         month=ca.get(Calendar.MONTH)+1;
        thismonth=ca.get(Calendar.MONTH)+1;
        thisyear=ca.get(Calendar.YEAR);
        this.userId=MainActivity.id;
        this.myList= (RecyclerView) findViewById(R.id.myList);
        this.noNetWork= (TextView) findViewById(R.id.noNetWork);
        noNetWork.setOnClickListener(new View.OnClickListener() { //去设置页面
            @Override
            public void onClick(View v) {
                Intent intent =  new Intent(Settings.ACTION_SETTINGS);
                startActivity(intent);
            }
        });
        loadingRel= (RelativeLayout) findViewById(R.id.loadingRel);
        title_bar.setText("管理效率 （"+month+"月"+")");
        setVisibleOGone(1);
    }

    public void initRecycle(){
        LinearLayoutManager manager = new LinearLayoutManager(this);
        myList.setLayoutManager(manager);
        manager.setOrientation(OrientationHelper.VERTICAL);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.lastMonth:
                setVisibleOGone(1);
                if (month==1){//上月是去年的
                    month=12;
                    year=year-1;
                    if (thisyear==year)
                        title_bar.setText(getResources().getString(R.string.person_manager_eff)+"("+month+getResources().getString(R.string.task_month)+")");
                    else
                        title_bar.setText(getResources().getString(R.string.person_manager_eff)+"（"+year+getResources().getString(R.string.task_year)+month+getResources().getString(R.string.task_month)+")");
                }else{
                    month=month-1;
                    if (thisyear==year)
                        title_bar.setText(getResources().getString(R.string.person_manager_eff)+"（"+month+getResources().getString(R.string.task_month)+")");
                    else
                        title_bar.setText(getResources().getString(R.string.person_manager_eff)+"（"+year+getResources().getString(R.string.task_year)+month+getResources().getString(R.string.task_month)+")");
                }
                LoadInfo(userId,year,month);
      //          adapter.notifyDataSetChanged();
                dialog.dismiss();

                break;
            case R.id.nowMonth://本月
                setVisibleOGone(1);
                month=thismonth;
                year=thisyear;
                title_bar.setText(getResources().getString(R.string.person_manager_eff)+"("+month+getResources().getString(R.string.task_month)+")");

                LoadInfo(userId,thisyear,thismonth);

                dialog.dismiss();

                break;
            case  R.id.nextMonth://下月
                setVisibleOGone(1);
                if (month==12){
                    year=year+1;
                    month=1;
                    if (thisyear==year)
                        title_bar.setText(getResources().getString(R.string.person_manager_eff)+"("+month+getResources().getString(R.string.task_month)+")");
                    else
                        title_bar.setText(getResources().getString(R.string.person_manager_eff)+"（"+year+getResources().getString(R.string.task_year)+month+getResources().getString(R.string.task_month)+")");
                }else{//=12就是下一年的数据
                    month=month+1;
                    if (thisyear==year)
                        title_bar.setText(getResources().getString(R.string.person_manager_eff)+"("+month+getResources().getString(R.string.task_month)+")");
                    else
                        title_bar.setText(getResources().getString(R.string.person_manager_eff)+"（"+year+getResources().getString(R.string.task_year)+month+getResources().getString(R.string.task_month)+")");
                }
                LoadInfo(userId,year,month);
            //    adapter.notifyDataSetChanged();
                dialog.dismiss();
                break;
            case R.id.closeDialog:
                dialog.dismiss();
                break;
        }

    }
    private void creatMoreDialog(){
        dialog=new Dialog(this,R.style.BottomDialog);
        View view= LayoutInflater.from(this).inflate(R.layout.efficdialog, (ViewGroup) getWindow().getDecorView(),false);
        TopDialogUtils.showTopDialog(this,dialog,view,3);
        Button closedialog= (Button) view.findViewById(R.id.closeDialog);
        closedialog.setOnClickListener(this);
        TextView lastMonth= (TextView) view.findViewById(R.id.lastMonth);
        lastMonth.setOnClickListener(this);
        TextView nowMonth= (TextView) view.findViewById(R.id.nowMonth);
        nowMonth.setOnClickListener(this);
        TextView nextMonth= (TextView) view.findViewById(R.id.nextMonth);
        nextMonth.setOnClickListener(this);
        LinearLayout linear2 = (LinearLayout) view.findViewById(R.id.Linear2);
        linear2.setVisibility(View.GONE);
//                TextView plan=(TextView)view.findViewById(R.id.taskPlan);
//                plan.setVisibility(View.GONE);
//                TextView managerTask= (TextView) view.findViewById(R.id.ManagerTask);
//                managerTask.setVisibility(View.GONE);
        dialog.show();
    }
    private void LoadInfo(int id, final int year, final int month){
        Map<String,String> map=new HashMap<>();
        map.put("task","getGLXLByEmpidandYM");
        map.put("empid", id+"");
        map.put("year",year+"");
        map.put("month",month+"");
        try {
            OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                @Override
                public void onSuccess(String result) {
                    String[] strings=result.split("\\|");
                    setVisibleOGone(2);
                    if(strings[0].equals("201")){
                        BaseActivity.showAnimaDialog(PersonEfficForOMActivity.this,strings[1]);
                    }else {
                        Gson gson = new Gson();
                        Type typeList = new TypeToken<ArrayList<ManagerEfficBean>>() {
                        }.getType();
                        melist=new ArrayList<>();
                        melist=gson.fromJson(pubClass.convertToArrayJson(result),typeList);
                        adapter=new PersonEfficRecycleAdapter(PersonEfficForOMActivity.this, melist, new PersonEfficRecycleAdapter.lookCallBack() {
                            @Override
                            public void lookOnclick(ManagerEfficBean bean) {
                                Intent in=new Intent(PersonEfficForOMActivity.this,ManageEfficMainActivity.class);
                                in.putExtra("userName",bean.getFirstName());
                                in.putExtra("userId",bean.getId());
                                in.putExtra("year",year);
                                in.putExtra("month",month);
                                startActivity(in);
                            }
                            @Override
                            public void underNumclick(ManagerEfficBean bean) {
                                if(bean.getSubEmp()==0){
                                    BaseActivity.showAnimaDialog(PersonEfficForOMActivity.this,"当前角色没有下属");
                                }else {
                                    userId=bean.getId();
                                    LoadInfo(userId,year,month);
                                    adapter.notifyDataSetChanged();
                                }
                            }
                        });
                        myList.setAdapter(adapter);
                        adapter.notifyDataSetChanged();

                    }
                }
                @Override
                public void onFailture() {
                    setVisibleOGone(3);
                    BaseActivity.showAnimaDialog(PersonEfficForOMActivity.this,"网络不是很好");
                }
            },map);
        } catch (IOException e) {
            e.printStackTrace();
            //请求失败
            BaseActivity.showAnimaDialog(PersonEfficForOMActivity.this,"网络请求失败！");
        }

    }


    //接收网络状态的判断广播
    NetWorkStateReceiver netWorkStateReceiver;
    int whetherConnectNetWork=0;
    @Override
    protected void onResume() {
        if (netWorkStateReceiver==null){
            netWorkStateReceiver=new NetWorkStateReceiver();
        }
        IntentFilter filter=new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkStateReceiver,filter);
        System.out.print("广播注册");
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(netWorkStateReceiver);
        System.out.print("广播注销");
    }

    //用于离线状态下的voice的点击
    class NetWorkStateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo!=null){
                whetherConnectNetWork=1;
                noNetWork.setVisibility(View.GONE);
                //判断数据是否已加载
                if (melist!=null&&melist.size()!=0);
                else{
                    //loads
                    setVisibleOGone(1);
                    LoadInfo(userId,year,month);
                }
            }else{
                whetherConnectNetWork=0;
                setVisibleOGone(3);
            }
        }
    }

    public void setVisibleOGone(int k){
        if (k==1){
            noNetWork.setVisibility(View.GONE);
            myList.setVisibility(View.GONE);
            loadingRel.setVisibility(View.VISIBLE);
        }
        if (k==2){
            myList.setVisibility(View.VISIBLE);
            loadingRel.setVisibility(View.GONE);
        }
        if (k==3){
            noNetWork.setVisibility(View.VISIBLE);
            loadingRel.setVisibility(View.GONE);
        }

    }

    //返回键有bug，因此设置


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            finish();
        }
        return true;
    }
}




